package cn.trs.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.compress.utils.IOUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @author:TRS
 * @create:2023/2/24 16:01
 * @description:http远程请求工具类
 * @ClassName: HttpPostRequest
 * @company TRS
 */
public class HttpPostRequest {

    public static String get(String urlStr) throws Exception{
        HttpURLConnection conn = null;
        try {
            //创建URL对象
            URL url = new URL(urlStr);
            //获取URL连接
            conn = (HttpURLConnection) url.openConnection();
            //设置通用的请求属性
            setHttpUrlConnection(conn, "GET");
            //建立实际的连接
            conn.connect();
            //获取响应的内容
            return readResponseContent(conn.getInputStream());
        } finally {
            if(null!=conn) conn.disconnect();
        }
    }

    public static String post(String urlStr, Map<String, Object> paramMap) throws Exception{
        HttpURLConnection conn = null;
        PrintWriter writer = null;
        try {
            // 创建URL对象
            URL url = new URL(urlStr);
            // 获取请求参数
            String param = getParamString(paramMap);
            // 获取URL连接
            conn = (HttpURLConnection) url.openConnection();
            //设置通用请求属性
            setHttpUrlConnection(conn, "POST");
            //建立实际的连接
            conn.connect();
            //将请求参数写入请求字符流中
            writer = new PrintWriter(conn.getOutputStream());
            writer.print(param);
            writer.flush();
            //读取响应的内容
            return readResponseContent(conn.getInputStream());
        } finally {
            if(null!=conn) conn.disconnect();
            if(null!=writer) writer.close();
        }
    }

    private static String readResponseContent(InputStream in) throws IOException {
        Reader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            reader = new InputStreamReader(in);
            char[] buffer = new char[1024];
            int head = 0;
            while( (head = reader.read(buffer)) > 0 ){
                content.append(new String(buffer, 0, head));
            }
            return content.toString();
        } finally {
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(in);
        }
    }

    /**
     * 设置Http连接属性
     * @param conn  http连接
     * @param requestMethod
     * @throws ProtocolException
     */
    private static void setHttpUrlConnection(HttpURLConnection conn, String requestMethod) throws ProtocolException {
        conn.setRequestMethod(requestMethod);
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("Accept-Language", "zh-CN");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
        conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
        if(null != requestMethod && "POST".equals(requestMethod)){
            conn.setDoOutput(true);
            conn.setDoInput(true);
        }
    }

    /**
     * 将参数转为路径字符串
     * @param paramMap 参数
     * @return
     */
    private static String getParamString(Map<String, Object> paramMap){
        if(null == paramMap || paramMap.isEmpty()){
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for(String key : paramMap.keySet() ){
            builder.append("&")
                    .append(key).append("=").append(paramMap.get(key));
        }
        return builder.deleteCharAt(0).toString();
    }

    /**
     * get请求
     *
     * @param path
     * @param param
     * @return
     */
    public static String get(String path,Map<String, Object> param) {
        try {
            if (param != null) {
                StringBuffer paramBuffer = new StringBuffer();
                int i = 0;
                for (String key : param.keySet()) {
                    if (i == 0)
                        paramBuffer.append("?");
                    else
                        paramBuffer.append("&");
                    paramBuffer.append(key).append("=").append(param.get(key));
                    i++;
                }
                path += paramBuffer;
            }
            URL url = new URL(path);    // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败!");
            return null;
        }
    }

    /**
     * post    请求
     *
     * @param path
     * @param jsonStr
     * @return
     */
    public static String post(String path,String jsonStr) {

        try {
            URL url =  new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
            httpURLConnection.setReadTimeout(10000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

//			PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
//			printWriter.write(postContent);
//			printWriter.flush();

            httpURLConnection.connect();
            OutputStream os=httpURLConnection.getOutputStream();
            os.write(jsonStr.getBytes("UTF-8"));
            os.flush();

            StringBuilder sb = new StringBuilder();
            int httpRspCode = httpURLConnection.getResponseCode();
            if (httpRspCode == HttpURLConnection.HTTP_OK) {
                // 开始获取数据
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("inputs", "%E7%94%A8%E6%88%B7%EF%BC%9A%E4%BD%A0%E5%A5%BD%5CnTRS%EF%BC%9A%E4%BD%A0%E5%A5%BD%EF%BC%8C%E6%88%91%E6%98%AF%E6%91%86%E7%83%82%E5%B0%8F%E5%AD%90%5Cn%E7%94%A8%E6%88%B7%EF%BC%9A%E4%BD%A0%E7%9F%A5%E9%81%93%E6%8B%93%E5%B0%94%E6%80%9D%E5%85%AC%E5%8F%B8%E5%A6%82%E4%BD%95%E5%98%9B%EF%BC%9F%5CnTRS%EF%BC%9A");
        paramMap.put("mobile", "13931157213");
        paramMap.put("password", "a83981816");
        paramMap.put("type", "login");
        try {
            JSONObject result= JSON.parseObject(HttpPostRequest.post("http://82.157.166.109:9000/api/predict/", paramMap));
            if(result.getIntValue("code") == 200){
                //获得的令牌
                String resultString=result.getString("result");
                System.out.println(URLDecoder.decode(resultString,"UTF-8"));
                //response.sendResirect(“ http://<domain>/interfaces/login?token= fd5tEMl5gYbSi9g9dgd3m8u2Oe1J7fkA&mobile=18600863155&timestamp=1468485098135&schoolId=1&productId=199&companyId=888”)
            }
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

